<template>
  <div>
    <div class="card-box">
      <el-card class="elcard" style="margin-right:10px;">
        <div slot="header" class="clearfix">
          <span class="tit">产学研协同趋势</span>
        </div>
        <div id="chartOne" style="width:100%;height:390px;"></div>
      </el-card>
      <el-card class="elcard" style="margin-left:10px;">
        <div slot="header" class="clearfix">
          <span class="tit">核心机构产学研合作</span>
        </div>
        <div id="chartTwo" style="width:100%;height:390px;"></div>
      </el-card>
    </div>
    <!-- 合作成果 -->
    <el-card class="elcard">
      <div slot="header" class="clearfix">
        <span class="tit">产学研成果转化</span>
        <span class="total" v-if="total>0">（检索结果约{{total}}条）</span>
      </div>
      <ul v-if="tableAllData.length>0">
        <li v-for="(item, index) in tableData" :key="index">
          <div class="info1">
            <div class="box">
              <div class="logo">
                <img :title="item.src" class="src-img" v-if="!item.srcImg" src="@/assets/img/default.png" alt="">
                <img :title="item.src" class="src-img" v-else :src="item.srcImg" alt="">
              </div>
              <h4 @click="goDetail(item.src)">{{item.src}}</h4>
            </div>
            <div class="box">
              <div class="logo">
                <img :title="item.target" class="target-img" v-if="!item.targetImg" src="@/assets/img/default.png" alt="">
                <img :title="item.target" class="target-img" v-else :src="item.targetImg" alt="">
              </div>
              <h4 @click="goDetail(item.target)">{{item.target}}</h4>
            </div>
          </div>
          <div class="info2">
            <ul class="info2-item">
              <li class="theader">
                <p>合作成果</p>
                <p>合作起始时间</p>
                <p>涉及专利数量</p>
              </li>
              <li v-for="(ite, j) in item.items" :key="j" @click="handdle(ite)" class="tbody">
                <p>{{ite.ipc_kind}}</p>
                <p>{{ite.start}}</p>
                <p>{{ite.count}}</p>
              </li>
            </ul>
            <div class="info2-item2">
              <p class="tit">产业标签</p>
              <div class="content">
                <p class="tags">
                  <span v-for="(it, b) in item.labels" :key="b" :title="it" :class="{uni3form: item.items.length<=1}">{{it}}</span>
                </p>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <ul v-else>
        <li class="no-data">{{noData}}</li>
      </ul>
      <el-col :span="24" style="text-align:center;padding:10px; 0">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :current-page.sync="ipi"
          :page-size="ips"
          :total="total">
        </el-pagination>
      </el-col>
    </el-card>
    <el-card class="elcard" style="margin-top:20px;">
      <div slot="header" class="clearfix">
        <span class="tit">合作关系图</span>
      </div>
      <div id="chartThree" style="width:100%;height:1000px;"></div>
    </el-card>
    <v-dialog-pn ref="DialogPartentDetail"></v-dialog-pn>
  </div>
  
</template>

<script>
import { mapState } from 'vuex'
import resize from '@/utils/resize'
import Colors from '@/utils/chartsColors'
import vDialogPn from '@/views/components/v-dialog-pn'
export default {
  mixins:[resize],
  components:{vDialogPn},
  data() {
    return {
      chartOne: null,
      chartTwo: null,
      chartThree: null,
      data: [],
      tableData: [],
      tableAllData: [],
      parTeamwork2Name: '',
      ips: 5,
      total: 0,
      ipi: 1,
      noData: '数据检索中...'
    }
  },
  computed:{
    ...mapState(['levelCode','levelName'])
  },
  methods: {
    goDetail(name){
      this.$Bus.$emit("progressBar", name)
    },
    getChartOneData() {
      this.chartOne.showLoading({
        text: 'loading',
        color: '#0b0a2b',
        textColor: '#0b0a2b',
        maskColor: '#fff',
        zlevel: 0
      })
      this.$post(this.$Url.production.cityAnalysis, {
        code: this.levelCode,
        shouldArr: {
          an1_type: [
            "高校",
            "院所"
          ]
        },
        aggs: {
          field: "ad",
          interval: "YEAR",
          format: "yyyy",
          type: "date"
        },
        rangArr: [
          {
            field: "ad",
            start: this.$DateManag().start,
            end: this.$DateManag().end
          },
          {
            field: "an_num",
            start: "2"
          }
        ]
      }).then(res => {
        let data = res.data || []
        let xAxisData = []
        let yAxisData = []
        for (let i in data) {
          xAxisData.push(data[i].key_as_string)
          yAxisData.push(data[i].doc_count)
        }
        let endYear = this.$DateManag().end.split('-')[0]
        if (xAxisData[xAxisData.length-1] !== endYear) {
          xAxisData.push(endYear)
          yAxisData.push(0)
        }
        this.renderChartOne(xAxisData, yAxisData)
      }).catch(err => {})
    },
    renderChartOne(xAxisData, yAxisData) {
      let yAxisData1 = yAxisData.slice(0,yAxisData.length-1)
      let yAxisData2 = ['-','-','-','-','-','-','-','-',yAxisData[[yAxisData.length-2]],yAxisData[[yAxisData.length-1]]]
      if(yAxisData[yAxisData.length-1]===0){
        yAxisData2 = ['-','-','-','-','-','-','-','-',yAxisData[[yAxisData.length-2]],yAxisData[[yAxisData.length-2]]]
      }
      let option = {
        tooltip: {
          confine: true,
          trigger: "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
              color: "#000"
          },
          formatter:function(params){
            let str = ''
            let val=[]
            // 先把两个两个值汇总
            params.forEach(i=>{
              val.push(i.data)
            })
            // 去掉'-'
            for(let i=0;i<val.length;i++){
              if(val[i]==="-"){
                val.splice(i,1)
                i--
              }
            }
            // 重合部分去重
            val = [...new Set(val)]
            // 拼接
            str+=params[0].axisValue+'<br/>'
            str+=params[0].seriesName + "："+ val
            return str
          },
          axisPointer: { type: "none" }
        },
        grid: {
          top: '20'
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: xAxisData,
          splitLine: {
          show: false,
            lineStyle: {
              color: "#f0f1f3"
            }
          },
          axisLine: {
            lineStyle: {
              color: "#f0f1f3",
              width: 2
            }
          },
          axisLabel: {
            textStyle: {
              color: "#9e9e9e"
            }
          }
        },
        yAxis: {
          type: "value",
          splitLine: {
            show: true,
            lineStyle: {
                color: "#f0f1f3"
            }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
                color: "#f0f1f3",
                width: 2
            }
          },
          axisLabel: {
            textStyle: {
                color: "#9e9e9e"
            }
          }
        },
        dataZoom: [
          {
            id: 'dataZoomX',
            type: 'inside',
            xAxisIndex: [0],
            filterMode: 'filter'
          }
        ],
        series: [
          {
            type: 'line',
            name: '趋势',
            color: Colors.color[0],
            smooth: 1,
            data: yAxisData1,
            areaStyle: {
              color:'#AA9EC5',
              opacity: .5
            }
            /* areaStyle: {
              normal: {
                type: 'radial',
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                      offset: 0, color: "rgba(" + Colors.rgb[0] + ",0.3)" // 0% 处的颜色
                  }, {
                      offset: 1, color: "rgba(" + Colors.rgb[0] + ",0.01)" // 100% 处的颜色
                  }],
                  // global: false // 缺省为 false
                },
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowBlur: 10
              }
            } */
          },
          {
            type: 'line',
            name: '趋势',
            color: Colors.color[0],
            smooth: 1,
            data: yAxisData2,
            lineStyle:{
              type:'dotted'
            },
            areaStyle: {
              color:'#AA9EC5',
              opacity: .5
            }
            /* areaStyle: {
              normal: {
                type: 'radial',
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                      offset: 0, color: "rgba(" + Colors.rgb[0] + ",0.3)" // 0% 处的颜色
                  }, {
                      offset: 1, color: "rgba(" + Colors.rgb[0] + ",0.01)" // 100% 处的颜色
                  }],
                  // global: false // 缺省为 false
                },
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowBlur: 10
              }
            } */
          }
        ]
      }
      this.chartOne.hideLoading()
      this.chartOne.setOption(option, true)
    },
    getChartTwoData() {
      this.chartTwo.showLoading({
        text: 'loading',
        color: '#0b0a2b',
        textColor: '#0b0a2b',
        maskColor: '#fff',
        zlevel: 0
      })
      this.$post(this.$Url.production.cityAnalysis, {
        code: this.levelCode,
        shouldArr: {
          an1_type: ["高校","院所"] 
        },
        aggs: [
          {
            size: "10",
            field: "an1",
            type: "base",
            subAggs: {
              size: "10",
              field: "ipc_kind",
              type: "base"
            }
          }
        ],
        rangArr: [
          {
            field: "an_num",
            start: "2"
          }
        ]
      }).then(res => {
        let buckets = res.data || []
        if (buckets.length > 0) {
          this.parTeamwork2Name = buckets[0].key
          this.$store.commit('setSynergyFirstCompanyName', this.parTeamwork2Name)
          this.getTableAllData()
        } else {
          this.noData = '暂无数据'
        }
        
        let legendData = []
        let xArr = []
        let seriesData = []
        let newData = []
        for(let i in buckets){
          let bbuckets = buckets[i].child || []
          let arr = []
          for (let j in bbuckets) {
            let obj = {
              key: bbuckets[j].key,
              count: bbuckets[j].doc_count
            }
            arr.push(obj)
            xArr.push(bbuckets[j].key)
          }
          newData.push({
            name: buckets[i].key,
            data: arr
          })
          legendData.push(buckets[i].key)

        }
        xArr = Array.from(new Set(xArr))
        let dataSource = []
        for (let i in xArr) {
          let arr = [xArr[i]]
          for (let j in newData) {
            let count = 0
            f: for (let k in newData[j].data) {
              if (newData[j].data[k].key === xArr[i]) {
                count = newData[j].data[k].count
                break f
              }
            }
            arr.push(count)
          }
          dataSource.push(arr)
        }
        let firstArr = ['product', ...legendData]
        dataSource = [firstArr, ...dataSource]

        for(let i in xArr) {
          seriesData.push({
            type: 'bar',
            barMaxWidth: '18',
            smooth: true,
            stack: 'all',
            seriesLayoutBy: 'row',
            color: i > 50 ? Colors.color[i % 50] : Colors.color[i]
          })
        }
        this.renderChartTwo(dataSource, seriesData)
      })
    },
    renderChartTwo(dataSource, seriesData) {
      let option = {}
      option = {
        animation: false,
        tooltip: {
          confine: true,
          show: true,
          type: "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
            color: "#000"
          },
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        // legend: {
        //   type: "scroll",
        //   top: '20px',
        //   orient: 'horizontal',
        // },
        grid: {
          top: '10px',
          left: '40px',
          right: '20px',
          bottom: '120px'
        },
      }
      
      option = {
        ...option,
        
        dataset: {
          source: dataSource
        },
        xAxis: [
          {
            type: "category",
            triggerEvent:true,
            boundaryGap: true,
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              interval: 0,
              rotate: 40,
              color: '#7d90ae'
            },
            axisLabel: {
              formatter: function(params) {
                var ret = ""; //拼接加\n返回的类目项
                var maxLength = 10; //每项显示文字个数
                var valLength = params.length; //X轴类目项的文字个数
                var rowN = Math.ceil(valLength / maxLength); //类目项需要换行的行数
                if (rowN > 1) {
                  //如果类目项的文字大于3,
                  for (var i = 0; i < rowN; i++) {
                    var temp = ""; //每次截取的字符串
                    var start = i * maxLength; //开始截取的位置
                    var end = start + maxLength; //结束截取的位置
                    //这里也可以加一个是否是最后一行的判断，但是不加也没有影响，那就不加吧
                    temp = params.substring(start, end) + "\n";
                    ret += temp; //凭借最终的字符串
                  }
                  return ret;
                } else {
                  return params;
                }
              },
              margin: 14,
              textStyle: {
                color: "#9e9e9e"
              },
              rotate: 45,
              interval: 0
            }
            
          }
        ],
        yAxis: [
          {
            type: "value",
            minInterval: 1,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#7d90ae'
            },
            splitLine: {
              lineStyle: {
                color: '#d3dbea',
                type: 'dashed'
              }
            },
          }
        ],
        series: seriesData
      }
      this.chartTwo.hideLoading()
      this.chartTwo.setOption(option, true)
      let that = this
      this.chartTwo.on('click', function (params) {
        if(params.componentType == "xAxis"){
          let val = {name:params.value,type:'org'}
          that.$Bus.$emit("progressBar", val)
        }
      })
    },
    getChartThreeData() {
      this.$post(this.$Url.organization.cooperate, {
        code: this.levelCode,
        aggs: {
          size: "10",
          field: "an1",
          type: "base",
          subAggs: {
            size: "50",
            field: "an",
            type: "base",
            subAggs: {
              size: "500",
              field: "pn",
              type: "base"
            }
          }
        },
        shouldArr: {
          an1_type: [
            "高校",
            "院所"
          ]
        },
        rangArr: [
          {
            field: "an_num",
            start: "2"
          }
        ]
      }).then(res => {
        let data = res.data || []
        this.data = JSON.parse(JSON.stringify(data))
        let link = []
        let node = []
        // 取关系
        for(let i in data){
          node.push(data[i].src)
          node.push(data[i].target)
          link.push({
            source: data[i].src,
            target: data[i].target,
            value: data[i].count,
            info:data[i].info
          })
        }
        // 取节点
        node = Array.from(new Set(node))
        let nodejson = []
        for(let i in node){
          nodejson.push({
            name: node[i]
          })
        }
        this.renderChartThree(nodejson, link)
      }).catch(err => {})
    },
    renderChartThree(node, link) {
      let option = {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'item',
          triggerOn: 'mousemove'
        },
        color: Colors.color,
        series: [
          {
            type: 'sankey',
            data: node,
            left: 30,
            right: 230,
            links: link,
            draggable:false,
            focusNodeAdjacency: false,
            itemStyle: {
                borderWidth: 1,
                borderColor: '#aaa',
                fontSize: '10px'
            },
            lineStyle: {
                color: 'source',
                curveness: 0.5
            },
            lable:{
                fontSize:'9'
            }
          }
        ]
      }
      this.chartThree.setOption(option)
      let that = this
      this.chartThree.on('click',function(prim){
        if(prim.dataType === 'node'){
          isComapny(prim.name)
        }else{
          if(prim.data.info) that.$refs.DialogPartentDetail.init(prim.data.info)
        }
      })
      // 判断机构或者是企业
      function isComapny(name){
        let eid =''
        that.$get(that.$Url.company.getCompanyId, {
          keyWord: name
        }).then((res) => {
          let datas = res.data
          if(datas){
            eid = datas.result[0]._id
            that.$get(`${that.$Url.organization.isComapny}/?eid=${eid}`,{})
            .then(data=>{
              // false 不是公司
              if(data.data == false){
                let val = {name:name,type:'org',eid:eid}
                that.$Bus.$emit("progressBar", val)
              }else{
                let val = {name:name,type:'company',eid:eid}
                that.$Bus.$emit("progressBar", val)
              }
            }).catch(e=>{console.log(e)})
          }
        }).catch(e=>{console.log(e)})
      }
    },
    // 表格行点击
    handdle(row){
      if(row.pns) this.$refs.DialogPartentDetail.init(row.pns)
    },
    getTableAllData() {
      this.noData = '数据检索中...'
      this.$get(this.$Url.production.parTeamwork2, {
        province: this.levelName,
        cityCode: this.levelCode,
        name: this.parTeamwork2Name
      }).then(res => {
        let data = res.data || []
        this.tableAllData = JSON.parse(JSON.stringify(data))
        this.total = this.tableAllData.length
        if (this.tableAllData.length > 0) {
          this.tableData = this.tableAllData.slice((this.ipi - 1) * this.ips, this.ipi * this.ips)
          this.tableData.forEach(v => {
            this.getImg(v.src, (imgData) => {
              this.$set(v, 'srcImg', imgData)
            })
            this.getImg(v.target, (imgData) => {
              this.$set(v, 'targetImg', imgData)
            })
          })
        } else {
          this.noData = '暂无数据'
        }
      })
    },
    getTableData() {
      this.tableData = this.tableAllData.slice((this.ipi - 1) * this.ips, this.ipi * this.ips)
      this.tableData.forEach(v => {
        this.getImg(v.src, (imgData) => {
          this.$set(v, 'srcImg', imgData)
        })
        this.getImg(v.target, (imgData) => {
          this.$set(v, 'targetImg', imgData)
        })
      })
    },
    getImg(companyName, func) {
      let promise = new Promise((resolve, reject) => {
        this.$post(this.$Url.search.companyList, {
          name: companyName,
          ipi: 1,
          ips: 1
        }).then(res => {
          let data = res.data
          if (data) {
            let eid = data.result && data.result[0]._id
            resolve(eid)
          }
        }).catch(err => {})
      })
      promise.then((eid) => {
        this.$get(this.$Url.search.companyLogo, {
          eid: eid
        }).then(res => {
          let data = res.data
          if (data) {
            return func(data)
          }
        }).catch(err => {})
      })
    },
    // 分页
    handleCurrentChange(val){
      this.ipi = val
      this.getTableData()
    },
    headerCellStyle() {
      return {
        'font-weight': 'normal',
        'color': '#86899e',
        'background-color': '#f3f6f9'
      }
    }
  },
  mounted() {
    this.chartOne = this.$echarts.init(document.getElementById('chartOne'))
    this.chartTwo = this.$echarts.init(document.getElementById('chartTwo'))
    this.chartThree = this.$echarts.init(document.getElementById('chartThree'))
    this.getChartOneData()
    this.getChartTwoData()
    this.getChartThreeData()
  }
}
</script>

<style lang="scss" scoped>
.card-box {
  position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.elcard {
  flex: .5;
  text-align: left !important;
  .tit {
    font-size: 14px;
    font-weight: bold;
  }
  .total {
    font-size: 11px;
  }
}
.eltable {
  font-size: 14px;
  color: #4f515b;
  .company-box {
    display: flex;
    align-items: center;
    justify-content: center;
    .icon-box {
      position: relative;
      padding-left: 10px;
      padding-right: 60px;
      img {
        display: block;
        width: 60px;
        height: 60px;
        border: 4px solid #fff;
        border-radius: 50%;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
        &.target-img {
          position: absolute;
          top: 0;
          right: 20px;
        }
      }
    }
    .names {
      flex: 1;
      font-size: 16px;
      font-weight: bold;
      span {
        display: block;
        // width: 100%;
      }
    }
  }
  .results {
    font-weight: bold;
    color: #504da6;
  }
  .status {
    display: inline-block;
    padding: 4px 16px;
    border-radius: 18px;
    font-weight: bold;
    color: #504da6;
    background-color: #edeafc;
  }
}


.info1 {
  position: relative;
  display: flex;
  .box {
    position: relative;
    flex: 1;
    min-width: 0;
    height: 60px;
    margin: 10px 0;
    .logo {
      position: absolute;
      top: 0;
      left: 4px;
      width: 60px;
      height: 60px;
      border-radius: 50%;
      box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
      img {
        display: block;
        width: 60px;
        height: 60px;
        border: 4px solid #fff;
        border-radius: 50%;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
      }
    }
    h4 {
      position: relative;
      line-height: 60px;
      padding-left: 80px;
      padding-right: 20px;
      font-size: 16px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
    }
  }
}
.info2 {
  display: flex;
  .info2-item {
    position: relative;
    flex: .75;
    list-style: none;
    .theader {
      display: flex;
      padding: 10px 0;
      border-bottom: 1px solid #EBEEF5;
      color: rgb(134, 137, 158);
      background-color: rgb(243, 246, 249);
      > p {
        flex: 1;
        position: relative;
        line-height: 23px;
        padding-left: 10px;
        padding-right: 10px;
        vertical-align: middle;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: normal;
        word-break: break-all;
      }
    }
    .tbody {
      display: flex;
      width: 100%;
      padding: 10px 0;
      border-bottom: 1px solid #EBEEF5;
      box-sizing: border-box;
      &:hover {
        background-color: #f3f6f9;
        cursor: pointer;
      }
      > p {
        flex: 1;
        position: relative;
        line-height: 23px;
        padding-left: 10px;
        padding-right: 10px;
      }
    }
  }
  .info2-item2 {
    position: relative;
    flex: .25;
    .tit {
      line-height: 23px;
      padding: 10px;
      border-bottom: 1px solid #EBEEF5;
      vertical-align: middle;
      color: #86899E;
      background-color: #F3F6F9;
    }
    .content {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: calc(100% - 44px);
      border-left: 1px solid #EBEEF5;
      border-right: 1px solid #EBEEF5;
      border-bottom: 1px solid #EBEEF5;
      box-sizing: border-box;
    }
  }
}
.tags {
  position: relative;
  span {
    display: inline-block;
    width: 80px;
    line-height: 24px;
    padding: 0 10px;
    border-radius: 4px;
    margin-right: 10px;
    margin-bottom: 4px;
    text-align: center;
    font-size: 12px;
    color: #fff;
    background-color: $mainColor;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>